# -*- coding:utf-8 -*-
__author__ = "daoyu"
__date__ = "2023-6-29"
__doc__ = "封装yagmail"

import yagmail
import traceback
import os,sys
sys.path.append(os.getcwd())
from datetime import datetime
from utils.logger_client import logger
from utils.yaml_client import YamlClient

class YagMail:
    
    def __init__(self, sender=YamlClient().load_yaml(r"conf\mail_config.yaml")["sender"]):
        """
            初始化
        """
        self.sender = sender
        self.__yag = self.__SMTP()

    def __SMTP(self):
        """
            获取邮箱连接对象
        """
        return yagmail.SMTP(**self.sender)
    
    def send(self, contents,
            receivers=YamlClient().load_yaml(r"conf\mail_config.yaml")["receivers"],
            cc=YamlClient().load_yaml(r"conf\mail_config.yaml")["cc"],
            active=YamlClient().load_yaml(r"conf\mail_config.yaml")["active"]
            ):
        """
            发送邮件
        """
        subjiect = f"TGU接口自动化测试报告_{datetime.now()}"
        attachments = r"log\tgu_apitest.log"
        if active:
            logger.info("邮件已启用，开始发送邮件")
            try:
                self.__yag.send(to=receivers, cc=cc, subject=subjiect, contents=contents, attachments=attachments)
            except:
                traceback.print_exc()
                logger.error("邮件发送异常")
            else:
                logger.success("邮件发送成功")
        else:
            logger.warning("邮件未启用，请进行配置")